package com.iaiai.calendar.activity;

import java.text.ParseException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.iaiai.calendar.util.DateUtil;
import com.iaiai.calendar.util.LunarCalendar;
import com.iaiai.calendar.util.SolarTerms;

/**
 * 
 * <p>
 * Title: MainActivity.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2011-12-27
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class MainActivity extends Activity implements OnTouchListener {

	private ProgressDialog loadingDialog; // loading

	private final int yearStart = 1901;
	private final int yearEnd = 2050;
	private AlertDialog.Builder yearAlert;
	private AlertDialog.Builder monthAlert;

	private TextView monthTextView;
	private TextView yearTextView;
	private TextView jinriTextView; // 今日
	private TextView dayTextView; // 今日
	private TextView shengxiaoTextView; // 生肖
	private TextView constellationTextView; // 星座

	private ViewFlipper viewFlipper;
	private GestureDetector detector;

	private LinearLayout gridView1;
	private LinearLayout gridView2;
	private LinearLayout gridView3;

	private LinearLayout layout;

	private void init() {
		setTitle(R.string.app_title);
		
		Calendar calToday = Calendar.getInstance(); // 今日

		loadingDialog = new ProgressDialog(this);
		loadingDialog.setMessage("Loading...");

		yearTextView = (TextView) findViewById(R.id.year);
		monthTextView = (TextView) findViewById(R.id.month);
		shengxiaoTextView = (TextView) findViewById(R.id.shengxiao);
		constellationTextView = (TextView) findViewById(R.id.constellation);
		jinriTextView = (TextView) findViewById(R.id.jinri);
		dayTextView = (TextView) findViewById(R.id.day);
		layout = (LinearLayout) findViewById(R.id.layout);
		viewFlipper = new ViewFlipper(this);
		viewFlipper.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		yearTextView.setText(String.valueOf(DateUtil.getYear()));
		monthTextView.setText((DateUtil.getMonth() + 1) + "月");

		LunarCalendar lunarCalendar = new LunarCalendar(calToday);
		dayTextView.setText(DateUtil.getDate() + " / " + lunarCalendar);
		shengxiaoTextView.setText("属" + shengxiao(lunarCalendar));
		constellationTextView.setText(DateUtil.getConstellation(calToday
				.getTime()));
		// tgdzTextView.setText(getTgdzYear(lunarCalendar) + " " +
		// LunarCalendar.getZhiMonth(cal.getTime()));

		gridView1 = new CalendarGridView(this, calToday);
		calToday.add(Calendar.MONTH, 1);
		gridView2 = new CalendarGridView(this, calToday);
		calToday.add(Calendar.MONTH, -2);
		gridView3 = new CalendarGridView(this, calToday);

		viewFlipper.addView(getGridLayout(gridView1));
		viewFlipper.addView(getGridLayout(gridView2));
		viewFlipper.addView(getGridLayout(gridView3));

		GestureListener gestureListener = new GestureListener(this, viewFlipper);
		gestureListener.setHandler(new GestureListener.Handler() {
			public void onChange() {
				CalendarGridView gridView = (CalendarGridView) ((LinearLayout) viewFlipper
						.getCurrentView()).getChildAt(1);

				yearTextView.setText(String.valueOf(DateUtil.getYear(gridView
						.getCalendar().getTime())));
				monthTextView.setText((DateUtil.getMonth(gridView.getCalendar()
						.getTime()) + 1) + "月");
			}

			public void onAnimationEnd(GestureListener.Direction direction) {
				// 新建线程运行
				ref(direction);
			}
		});
		detector = new GestureDetector(this, gestureListener);
		layout.addView(viewFlipper);

		yearTextView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setYearAlert(yearTextView.getText().toString()); // 设置年选择
			}
		});
		monthTextView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setMonthAlert(monthTextView.getText().toString()
						.replace("月", ""));
			}
		});
		jinriTextView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setYearMonth();
			}
		});
		dayTextView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setYearMonth();
			}
		});
		// shengxiaoTextView.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// setYearMonth();
		// }
		// });
		// constellationTextView.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// setYearMonth();
		// }
		// });
	}

	/**
	 * 设置年月
	 */
	private void setYearMonth() {
		loadingDialog.show();
		final android.os.Handler handler = new android.os.Handler();
		new Thread() {
			public void run() {
				handler.post(new Runnable() {
					public void run() {
						refYearMonth(DateUtil.getYear(),
								DateUtil.getMonth() + 1);
						loadingDialog.cancel();
					}
				});
			}
		}.start();
	}

	/**
	 * 设置月选择
	 * 
	 * @param month
	 */
	private void setMonthAlert(final String month) {
		monthAlert = new AlertDialog.Builder(this);
		monthAlert.setTitle("月");

		CharSequence[] monthData = { "1月", "2月", "3月", "4月", "5月", "6月", "7月",
				"8月", "9月", "10月", "11月", "12月" };
		monthAlert.setSingleChoiceItems(monthData, Integer.parseInt(month) - 1,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, final int which) {
						dialog.dismiss();
						loadingDialog.show();
						final android.os.Handler handler = new android.os.Handler();
						new Thread() {
							public void run() {
								handler.post(new Runnable() {
									public void run() {
										refMonth(which + 1);
										loadingDialog.cancel();
									}
								});
							}
						}.start();
					}
				});
		monthAlert.show();
	}

	/**
	 * 设置年选择
	 * 
	 * @param currYear
	 */
	private void setYearAlert(String currYear) {
		yearAlert = new AlertDialog.Builder(this);
		yearAlert.setTitle("年");

		CharSequence[] yearData = new CharSequence[yearEnd - yearStart];
		for (int i = yearStart, j = 0; i < yearEnd; i++, j++) {
			yearData[j] = String.valueOf(i);
		}
		yearAlert.setSingleChoiceItems(yearData, Integer.parseInt(currYear)
				- yearStart, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, final int which) {
				dialog.dismiss();
				loadingDialog.show();
				final android.os.Handler handler = new android.os.Handler();
				new Thread() {
					public void run() {
						handler.post(new Runnable() {
							public void run() {
								refYear((which + yearStart));
								loadingDialog.cancel();
							}
						});
					}
				}.start();
			}
		});
		yearAlert.show();
	}

	/**
	 * 刷新年月
	 * 
	 * @param year
	 * @param month
	 */
	private void refYearMonth(int year, int month) {
		yearTextView.setText(year + "");
		monthTextView.setText(month + "月");

		Calendar cal = Calendar.getInstance();
		try {
			cal.setTime(DateUtil.formatDate(year + "-" + month + "-1"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		gridView1 = new CalendarGridView(this, cal);
		cal.add(Calendar.MONTH, 1);
		gridView2 = new CalendarGridView(this, cal);
		cal.add(Calendar.MONTH, -2);
		gridView3 = new CalendarGridView(this, cal);

		viewFlipper.removeAllViews();
		viewFlipper.addView(getGridLayout(gridView1));
		viewFlipper.addView(getGridLayout(gridView2));
		viewFlipper.addView(getGridLayout(gridView3));
	}

	/**
	 * 刷新月
	 * 
	 * @param month
	 */
	private void refMonth(Integer month) {
		monthTextView.setText(month + "月");

		String year = yearTextView.getText().toString();
		Calendar cal = Calendar.getInstance();
		try {
			cal.setTime(DateUtil.formatDate(year + "-" + month + "-1"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		gridView1 = new CalendarGridView(this, cal);
		cal.add(Calendar.MONTH, 1);
		gridView2 = new CalendarGridView(this, cal);
		cal.add(Calendar.MONTH, -2);
		gridView3 = new CalendarGridView(this, cal);

		viewFlipper.removeAllViews();
		viewFlipper.addView(getGridLayout(gridView1));
		viewFlipper.addView(getGridLayout(gridView2));
		viewFlipper.addView(getGridLayout(gridView3));
	}

	/**
	 * 刷新年
	 * 
	 * @param year
	 */
	private void refYear(Integer year) {
		yearTextView.setText(year.toString());
		String month = monthTextView.getText().toString().replace("月", ""); // 当前月
		String dy = year + "-" + month + "-1";

		Calendar cal = Calendar.getInstance();
		try {
			cal.setTime(DateUtil.formatDate(dy));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		gridView1 = new CalendarGridView(this, cal);
		cal.add(Calendar.MONTH, 1);
		gridView2 = new CalendarGridView(this, cal);
		cal.add(Calendar.MONTH, -2);
		gridView3 = new CalendarGridView(this, cal);

		viewFlipper.removeAllViews();
		viewFlipper.addView(getGridLayout(gridView1));
		viewFlipper.addView(getGridLayout(gridView2));
		viewFlipper.addView(getGridLayout(gridView3));
	}

	/**
	 * 计算生肖
	 * 
	 * @param lunarCalendar
	 *            农历
	 * @return
	 */
	private String shengxiao(LunarCalendar lunarCalendar) {
		int year = DateUtil.getYear();
		if (year > lunarCalendar.getYear()) { // 如果阳历是新的一年，但阴历还没过春节，这时阴历年是比阳历年小
			return DateUtil.getShengxiao(lunarCalendar.getYear());
		}
		try {
			// 获得立春(阳历)，立春肯定是在2月
			String lc = year
					+ "-2-"
					+ SolarTerms.getSolarTermNum(year,
							SolarTerms.SolarTermsEnum.LICHUN.name());
			long lctime = DateUtil.formatDate(
					new LunarCalendar(DateUtil.formatDate(lc)).getDate())
					.getTime();
			if (DateUtil.formatDate(lunarCalendar.getDate()).getTime() < lctime) {
				return DateUtil.getShengxiao(year - 1);
			} else {
				return DateUtil.getShengxiao(year);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 刷新
	 * 
	 * @param direction
	 *            方向
	 */
	private void ref(final GestureListener.Direction direction) {
		final android.os.Handler handler = new android.os.Handler();
		new Thread() {
			public void run() {
				// 先取出当前月
				final Calendar calendar = Calendar.getInstance();
				calendar.setTime(((CalendarGridView) ((LinearLayout) viewFlipper
						.getCurrentView()).getChildAt(1)).getCalendar()
						.getTime());

				handler.post(new Runnable() {
					public void run() {
						viewFlipper.setInAnimation(null);
						viewFlipper.setOutAnimation(null);
						// 搜索当前的view
						for (int i = 0; i < 3; i++) {
							if (viewFlipper.getChildAt(i) == viewFlipper
									.getCurrentView()) {
								if (direction == GestureListener.Direction.LEFT) { // 往左
									calendar.add(Calendar.MONTH, -1);
									if (i == 0) { // 如果是第一个，则更新最后一个
										viewFlipper.removeViewAt(2);
										gridView3 = new CalendarGridView(
												MainActivity.this, calendar);
										viewFlipper
												.addView(getGridLayout(gridView3));
									} else if (i == 2) { // 如果不是第一个，则更新前一个
										viewFlipper.removeViewAt(1);
										gridView2 = new CalendarGridView(
												MainActivity.this, calendar);
										viewFlipper.addView(
												getGridLayout(gridView2), 1);
									} else if (i == 1) {
										viewFlipper.removeViewAt(0);
										gridView1 = new CalendarGridView(
												MainActivity.this, calendar);
										viewFlipper.addView(
												getGridLayout(gridView1), 0);
									}
									viewFlipper.setDisplayedChild(i);
								} else if (direction == GestureListener.Direction.RIGHT) { // 往右
									calendar.add(Calendar.MONTH, 1);
									if (i == 2) { // 如果是最后一个，则更新第一个
										viewFlipper.removeViewAt(0);
										gridView1 = new CalendarGridView(
												MainActivity.this, calendar);
										viewFlipper.addView(
												getGridLayout(gridView1), 0);
									} else if (i == 1) { // 如果不是最后一个，则更新下一个
										viewFlipper.removeViewAt(2);
										gridView3 = new CalendarGridView(
												MainActivity.this, calendar);
										viewFlipper
												.addView(getGridLayout(gridView3));
									} else if (i == 0) {
										viewFlipper.removeViewAt(1);
										gridView2 = new CalendarGridView(
												MainActivity.this, calendar);
										viewFlipper.addView(
												getGridLayout(gridView2), 1);
									}
									viewFlipper.setDisplayedChild(i);
								}
								break;
							}
						}
					}
				});
			}
		}.start();
	}

	/**
	 * 获得gridView
	 * 
	 * @param gridView
	 * @return
	 */
	private View getGridLayout(LinearLayout gridView) {
		LinearLayout layout = new LinearLayout(this);
		layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		layout.setOrientation(LinearLayout.VERTICAL);
		layout.addView(new CalendarTitleView(this)); // 标题
		layout.addView(gridView);
		return layout;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		init();
	}

	public boolean onTouch(View v, MotionEvent event) {
		return this.detector.onTouchEvent(event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_about:
			new AlertDialog.Builder(this).setTitle("关于")
					.setPositiveButton(android.R.string.ok, null)
					.setMessage("日历 - 丸子\r\n\r\n版本:1.0\r\nQQ:176291935")
					.show();
			break;
		}
		return true;
	}

}
